package org.cloudlab.config;

import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置跨域访问CORS的配置
 *
 * @author Liu Yicong
 * @date 2023/9/6
 */
//@Configuration
//@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {


	@Bean
	public CorsFilter corsFilter() {
		//1. 添加 CORS配置信息
		CorsConfiguration config = new CorsConfiguration();
		//放行哪些原始域
		config.addAllowedOrigin("http://192.168.50.112:8080");
		//是否发送 Cookie
		config.setAllowCredentials(true);
		//放行哪些请求方式
		config.addAllowedMethod("*");
		//放行哪些原始请求头部信息
		config.addAllowedHeader("*");
		//暴露哪些头部信息
		//config.addExposedHeader("*");
		//2. 添加映射路径
		UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
		corsConfigurationSource.registerCorsConfiguration("/**",config);
		//3. 返回新的CorsFilter
		return new CorsFilter(corsConfigurationSource);
	}
//	@Bean
//	public CorsConfigurationSource corsConfigurationSource() {
//		CorsConfiguration configuration = new CorsConfiguration();
//		configuration.addAllowedOrigin("*"); // 允许所有来源
//		configuration.addAllowedMethod("*"); // 允许所有请求方法
//		configuration.addAllowedHeader("*"); // 允许所有请求头
//		configuration.setAllowCredentials(true); // 允许发送Cookie
//
//		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//		source.registerCorsConfiguration("/**", configuration); // 对所有路径生效
//		return source;
//	}

//	@Override
//	public void addResourceHandlers(ResourceHandlerRegistry registry) {
//		registry.addResourceHandler("/swagger-ui.html")
//				.addResourceLocations("classpath:/META-INF/resources/");
//	}
//
//	@Override
//	public void addCorsMappings(CorsRegistry registry) {
//		registry.addMapping("/**")
//				.allowCredentials(true)
//				.allowedHeaders("*")
//				.allowedOriginPatterns("*")
//				.allowedMethods("*");
//	}

}
